HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

JavaScript String Methods

JavaScript provides a rich set of built-in methods for working with strings

Basic String Methods

  • charAt(index):
  • charCodeAt(index):
  • concat(string1, string2, ...):
  • indexOf(searchValue, startIndex)::
  • lastIndexOf(searchValue, startIndex):
  • slice(startIndex, endIndex):
  • substring(startIndex, endIndex):
  • substr(startIndex, length):
  • toUpperCase():
  • toLowerCase():
  • trim():
  • replace(searchValue, newValue):

Basic String Methods

: Returns the character at the specified index.

Example

const str = "Hello";
console.log(str.charAt(0)); // Output: "H"

charCodeAt(index):

: Returns the Unicode value of the character at the specified index.

Example

const str = "Hello";
console.log(str.charCodeAt(0)); // Output: 72

concat(string1, string2, ...)

: Combines two or more strings and returns a new string.

Example

const str1 = "Hello";
const str2 = "World";
console.log(str1.concat(" ", str2)); // Output: "Hello World"

indexOf(searchValue, startIndex)

: Returns the index of the first occurrence of a specified value within the string, starting the search at the optional startIndex.

Example

const str = "Hello World";
console.log(str.indexOf("World")); // Output: 6

lastIndexOf(searchValue, startIndex):

Returns the index of the last occurrence of a specified value within the string, starting the search at the optional startIndex.

Example

const str = "Hello World";
console.log(str.lastIndexOf("o")); // Output: 7

slice(startIndex, endIndex):

Extracts a section of the string and returns it as a new string, starting from startIndex up to, but not including, endIndex.

Example

const str = "Hello World";
console.log(str.slice(6)); // Output: "World"

substring(startIndex, endIndex):

Similar to slice(), but does not support negative indices. It extracts characters between startIndex and endIndex (not including endIndex).

Example

const str = "Hello World";
console.log(str.substring(6, 11)); // Output: "World"

substr(startIndex, length):

Extracts a specified number of characters from the string, starting from startIndex, and returns them as a new string.

Example

const str = "Hello World";
console.log(str.substr(6, 5)); // Output: "World"

toUpperCase():

Converts the string to uppercase.

Example

const str = "hello";
console.log(str.toUpperCase()); // Output: "HELLO"

toLowerCase():

Converts the string to lowercase.

Example

const str = "HELLO";
console.log(str.toLowerCase()); // Output: "hello"

trim():

Removes whitespace from both ends of the string.

Example

const str = "   Hello World   ";
console.log(str.trim()); // Output: "Hello World"

replace(searchValue, newValue):

Replaces occurrences of searchValue with newValue in the string.

Example

const str = "Hello World";
console.log(str.replace("World", "Universe")); // Output: "Hello Universe"